package login

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/dchest/captcha"
)

type AdminLogin struct {
	beego.Controller
}

func (c *AdminLogin) AdminLogin() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "Session")
		c.ServeJSON()
	}()
	var addr = "/login/AdminLogin"
	res := resMes.Login{}
	user := &Admin.User{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	var err error
	o := orm.NewOrm()

	user.Account = c.GetString("Account")

	key := c.GetString("key")

	value := c.GetString("value")

	id := c.GetString("id")

	if user.Account == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("AccountNull"), addr, "AccountNull")
		return
	} else if key == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("KeyNull"), addr, "KeyNull")
		return
	} else if value == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("valueNull"), addr, "valuNull")
		return
	}
	sessionUnkown := c.Ctx.Request.Header["Session"]

	if len(sessionUnkown) == 0 {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}
	session := sessionUnkown[0]
	if session == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}
	//fmt.Println(key)

	err = o.QueryTable("user").Filter("Account__exact", user.Account).One(user)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "401", err, addr, err.Error())
		return
	} else if user.Key != key {

		c.Data["json"] = errorDeal.ErrLightMess(mes, "402", "密码错误")
		return
	}

	if !captcha.VerifyString(id, value) {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "403", "验证码错误")
		return
	}

	if err = session2.LinkSession(user, session); err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//fmt.Println(200)

	res.User = user
	res.Code = "200"
	c.Data["json"] = res

}
